package com.ozo.news.controller;

import com.auth0.jwt.JWT;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ozo.news.entity.*;
import com.ozo.news.service.*;
import com.ozo.news.util.*;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.oauth2.resource.OAuth2ResourceServerProperties;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/auth")
public class AuthController {

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private PermsService permsService;

    @Autowired
    private ImageService imageService;

    @Autowired
    private InterestService interestService;

    @Autowired
    private NewsService newsService;

    @PostMapping("/login")
    public AjaxResult login(@RequestBody User user, HttpSession session) {
        //从shiro中，获取一个Subject对象
        Subject subject = SecurityUtils.getSubject();
        //System.out.println(subject);
        //System.out.println(user);
        ShiroUser shiroUser = new ShiroUser();
        AuthenticationToken token = new UsernamePasswordToken(user.getUsername(), user.getPassword());
        if(token != null){
            try {
                subject.login(token);
                String resToken = JwtUtil.sign1(user.getUsername(), user.getPassword());
                System.out.println(resToken);
                if(resToken != null){
                    redisUtil.set(resToken, user.getUsername(), 60 * 60);
                    shiroUser.setToken(resToken);
                    return AjaxResult.success("成功",shiroUser);
                }
                session.setAttribute("username",user.getUsername());
                return null;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    @GetMapping("/info")
    public AjaxResult findUserInfo(@RequestHeader("X-Token") String token, HttpSession session){
        Boolean flag = JwtUtil.verify(token);
        String username = JwtUtil.getUserName(token);
        if(!flag){
            throw new RuntimeException("请重新登录");
        }else {
            ShiroUser shiroUser = new ShiroUser();
            shiroUser.setName(username);
            List<Role> roles = roleService.findRoleByUsername(username);
            List<String> roless = new ArrayList<String>();
            for (Role role:roles){
                roless.add(role.getRoleName());
            }
            shiroUser.setRoles(roless);
            //shiroUser.setAvatar("https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
            //shiroUser.setAvatar("D:/Gitworkplace/news/src/main/resources/image/2721.jpg");
            User user = userService.findUserByName(username);
            Image image = imageService.findImageByconnectId(user.getUserId());
            String imageUrl;
            String baseUrl = "http://localhost:8011/";
            if(image != null){
                imageUrl = baseUrl + image.getImageUrl();
            }else{
                imageUrl = baseUrl + "image/defaultAvater.png";
            }
            shiroUser.setAvatar(imageUrl);
            if(shiroUser == null){
                throw new RuntimeException("请重新登录1");
            }else {
                System.out.println(shiroUser);
                return AjaxResult.success("成功",shiroUser);
            }
        }
    }

    @PostMapping("/logout")
    public AjaxResult logout(@RequestHeader("X-Token") String token){
        SecurityUtils.getSubject().logout();
        redisUtil.del(token);
        return AjaxResult.success("成功");
    }

    @GetMapping("/interest")
    public AjaxResult findUserInterest(@RequestHeader("X-Token") String token, HttpSession session){
        Boolean flag = JwtUtil.verify(token);
        String username = JwtUtil.getUserName(token);
        if(!flag){
            throw new RuntimeException("请重新登录");
        }else {
            List<Interest> interest = interestService.findInterestByUsername(username);
            List<String> list = new ArrayList<>();
            for (Interest i:interest) {
                list.add(i.getInterestName());
            }
            PageHelper.startPage(1, 6);
            PageInfo<News> page = new PageInfo<News>(newsService.findNewsByClassifyName(list));
            return AjaxResult.success("成功", page.getList());
        }
    }

    @PostMapping("/register")
    public AjaxResult insertUser(@RequestBody Interest interest){
        if(interest != null){
            User user = interest.getUser1();
            user.setUserId(GuuidUtil.getUUID());
            Timestamp timestamp = new Timestamp(System.currentTimeMillis());
            user.setUserStatus("0");
            user.setEnrollTime(timestamp);
            userService.insertUser(user);
            userService.insertUserRole(user.getUserId(),301L);
            interest.setUser1(user);
            interestService.insertInterest(interest);
            System.out.println(user);
            System.out.println(interest);
        }
        return AjaxResult.success("成功");
    }

//    @GetMapping("/routes")
//    public AjaxResult getMenu(){
//        List<>
//    }

}
